package pw.orm.db;

import java.sql.*;

/**
 * @Author Eric
 * @Desc
 * @Date Create in 17-12-29 下午5:18
 * @Modified By
 */
public class DB {

    public static int update(Connection connection ,String sql ,Object [] params) throws SQLException{
        PreparedStatement preparedStatement = null;
        try{
            preparedStatement = prepareStatement(connection,sql,params);
            return preparedStatement.executeUpdate();
        }finally {
            if(preparedStatement != null)preparedStatement.close();
        }

    }

    public static Object save(Connection connection ,String sql ,Object [] params) throws SQLException{
        PreparedStatement preparedStatement = null;
        try{
            preparedStatement = prepareStatement(connection,sql,params);
            preparedStatement.executeUpdate();
            ResultSet resultSet = preparedStatement.getGeneratedKeys();

            if (resultSet.next()) {
                return resultSet.getObject(1);
            }else {
                return null;
            }
        }finally {
            if(preparedStatement != null)preparedStatement.close();
        }

    }

    public static ResultSet select(Connection connection ,String sql ,Object [] params) throws SQLException{
        PreparedStatement preparedStatement = prepareStatement(connection,sql,params);
        return preparedStatement.executeQuery();
    }

    private static PreparedStatement prepareStatement(Connection connection ,String sql ,Object [] params) throws SQLException {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
        } catch (SQLFeatureNotSupportedException e) {
            try {
                preparedStatement = connection.prepareStatement(sql);
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw e1;
            }
        }
        if(params ==null || params.length == 0) return preparedStatement;
        for(int i=0;i<params.length;i++){
            preparedStatement.setObject(i+1, params[i]);
        }
        return preparedStatement;
    }

}
